var request = require('request');
var cheerio = require('cheerio');
var express = require('express');
var app = express();

var jsonarr = [];

function getHtml(url){
	request({url:'https://www.xzw.com'+url},function(error, response, body) {
		var $ = cheerio.load(body);
		var json = {};
		json.nametag = $('.info_box .info h1 .f_yh').text();
		json.xzdate = $('.info_box .info h1 small').text();
		json.xzsx = $('.info_box .info h1 em').text();
		json.xzjj = $('.info_box .info dl dd p').text();
		jsonarr.push(json);
	})
}

function setTimenum(fuc,num,time){
	var i = 0;
	if(isNaN(num)&&num.constructor == Array&&time==undefined){
		num.forEach(function(obj){
			setTimenum(fuc,1,obj*1000);
		})
	}else if(num){
		var timeout = setInterval(function(){
			if(i<num){
				fuc();
				i++;
			}else{
				clearInterval(timeout);
			}
		},time)
	}
}

function getjson(){
	request('https://www.xzw.com/astro/aries/',function(error, response, body) {
		var $ = cheerio.load(body);
		console.log($('.info_box .info').text())
		var arr = new Array();
		$('a').each(function(){
			if($(this).attr('hidefocus') == 'true'){
				var url = $(this).attr('href');
				console.log(url)
				arr.push(url)
			}
		})

		for(i in arr){
			getHtml(arr[i])
		}
	})
}


if(jsonarr==[]){
	
}else{
	getjson();
}

app.get('/',function(req,res){
	
	var timeout = setInterval(function(){
		if(jsonarr!=[]){
			res.send(jsonarr);
			console.log(jsonarr.length);
			clearInterval(timeout);
		}
	},1000)
})

var server = app.listen(8082, function () {
 
  var host = server.address().address
  var port = server.address().port
 
  console.log("应用实例，访问地址为 http://%s:%s", host, port)
 
})






// setTimenum(function(){
// 	console.log('123');
// },1,1000)


//w = (d + 1+ 2*m+3*(m+1)/5+y+y/4-y/100+y/400)%7  //蔡勒公式计算星期几  1，2月做13，14算
// function getweek(date){
// 	var Year = date.getFullYear()
// 	var Month = date.getMonth()+1
// 	var Day = date.getDate()
// 	if(Month == 1||Month == 2){
// 		Month += 12; 
// 	}
// 	console.log(Year+"-"+Month+"-"+Day)
// 	return Math.round(((Day + 2*Month + 3*(Month+1)/5 + Year + Year/4 - Year/100 + Year/400) % 7))
// }

// console.log(getweek(new Date('2017-5')));






// function 方法(回调,参数){
// 	if(!参数){
// 		回调();
// 	}
// 	回调(参数);
// }

// 方法(function(返回的参数){
// 	console.log(返回的参数);
// },'com')
